<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://yfcmf.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: rainfer <rainfer520@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\AuthRule as AuthRuleModel;
use app\common\controller\Common;
use app\common\model\Module as ModuleModel;
use think\facade\Env;

/**
 * 后台基控制器
 * @author rainfer <rainfer520@qq.com>
 */
class Base extends Common
{
    /**
     * 初始化
     * @throws
     */
    public function initialize()
    {
        parent::initialize();
        //检测登录
        if (!$this->checkAdminLogin()) {
            $this->redirect(config('yfcmf.adminpath') . '/Login/index');
        }

        $auth = new AuthRuleModel;
        //检测权限
        $id_curr = $auth->getUrlId();

        if (!$auth->checkAuth($id_curr)) {
            $this->error('没有权限', config('yfcmf.adminpath') . '/Index/index');
        }

        //获取有权限的菜单
        if (request()->module() == 'admin' && request()->controller() == 'Index') {
            $menus = $auth->getIndexRules(session('admin_auth.aid'));
            $id_index = $auth->getUrlId('admin/Index/index');
        } else {
            $menus = $auth->getRules(session('admin_auth.aid'), request()->module());
            $id_index = $id_curr;
        }
        //模块
        $module_model = new ModuleModel();
        $modules_nav = $module_model->where([['status', '=', 1], ['nav_url', 'neq', '']])->order('sort')->select();
        $this->assign('modules_nav', $modules_nav);
        $this->assign('menus', $menus);
        $id_curr_arr = $auth->getParents($id_curr);
        $this->assign('id_curr_arr', $id_curr_arr);
        $this->assign('id_index', $id_index);
    }
    /**
     * 空操作
     * @throws
     */
    public function _empty()
    {
        return $this->fetch('public/404');
    }




    /*
         * 公共导出方法
         */
    public function export_public($name='导出',$headArr=[],$data=[])
    {
//        $headArr=['表头1','表头2','表头3'];
//        $data=[
//            ['a1','a2','a3'],
//            ['1表头1','1表头2','1表头3'],
//            ['2表头1','2表头2','2表头3'],
//        ];
        //        PHPEx
        require_once Env::get('ROOT_PATH')."vendor/PHPExcel.php";
        //3.实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        //4.激活当前的sheet表
      //  $objPHPExcel->setActiveSheetIndex(0);

        //5.表头
        $objPHPExcel->getProperties();
        $key=ord('A');//设置表头
        foreach ($headArr as $v) {

            $colum = chr($key);

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);

            $key += 1;

        }

        $column = 2;

        $objActSheet = $objPHPExcel->getActiveSheet();

        foreach ($data as $key => $rows) { // 行写入

            $span = ord("A");

            foreach ($rows as $keyName => $value) { // 列写入

                $objActSheet->setCellValue(chr($span) . $column, $value);

                $span++;

            }

            $column++;

        }


        //7.设置保存的Excel表格名称
        $filename = $name.date('ymd',time()).'.xls';
        //8.设置当前激活的sheet表格名称；
        $objPHPExcel->getActiveSheet()->setTitle($name);
        //9.设置浏览器窗口下载表格
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:inline;filename="'.$filename.'"');
        //生成excel文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        //下载文件在浏览器窗口
        $objWriter->save('php://output');
        exit;
    }


    /*
     * 获取导入excel的数据
     */
    public function importExcel($file){
        require_once Env::get('ROOT_PATH')."vendor/PHPExcel.php";
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array('memoryCacheSize' => '16MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);//文件缓存
        //当前空间不用\，非当前空间要加\
        $PHPExcel = new \PHPExcel();//创建一个excel对象
        $PHPReader = new \PHPExcel_Reader_Excel2007(); //建立reader对象，excel—2007以后格式
        if (!$PHPReader->canRead($file)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();//建立reader对象，excel—2007以前格式
            if (!$PHPReader->canRead($file)) {
                $msg = '不是excel格式文件';
                $this->apiReturn(303,$msg);
            }
        }
        $PHPExcel = $PHPReader->load($file); //加载excel对象
        $sheet = $PHPExcel->getSheet(0); //获取指定的sheet表
        $rows = $sheet->getHighestRow();//行数
        $cols = $sheet->getHighestColumn();//列数

        $data = array();
        for ($i = 1; $i <= $rows; $i++){ //行数是以第1行开始
            $count = 0;
            for ($j = 'A'; $j <= $cols; $j++) { //列数是以A列开始
                $value = $sheet->getCell($j . $i)->getValue();
                if ($value) {
                    $data[$i - 1][$count] = (string)$sheet->getCell($j . $i)->getValue();
                    $count += 1;
                }
            }
        }
        return $data;
    }

    //文件上传
    public function upload(){

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->validate(['size'=>515678,'ext'=>'xls,ee'])
            ->move( Env::get('ROOT_PATH').'/data/upload_excel/');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            return Env::get('ROOT_PATH').'data/upload_excel'.'/'.$info->getSaveName();

        }else{
            // 上传失败获取错误信息
            $this->error($file->getError());
            //   echo $file->getError();
        }
    }

}
